/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BALibrarySettings.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 14/08/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BALibrarySettings.h"
#import "UIColor+HTML.h"
#import "UIImage+MultiplyColor.h"
#import "BABranch.h"
#import "BASettingsUserDefaultsKeys.h"
#import "UIColor+HTML.h"
#import "JSONEncodingHelperMethods.h"
#import "BACustomNavigationBar.h"


@interface BALibrarySettings () {
    NSMutableDictionary* iconImagesForSize;
    NSMutableDictionary* iconFileNamesForTypeString;
    
    UIColor* customerColorDark;
    UIColor* customerColorNormal;
}

@end


@implementation BALibrarySettings

SINGLETON_IMPL_GCD(BALibrarySettings)

@synthesize libraryObject = _libraryObject;

- (id)init
{
    self = [super init];
    if (self) {
        iconImagesForSize = [NSMutableDictionary new];
        iconFileNamesForTypeString = [NSMutableDictionary new];
        
        customerColorDark = BA_CUSTOM_NAVBAR_DEFAULT_GRAY_COLOR;
        customerColorNormal = BA_CUSTOM_NAVBAR_DEFAULT_GRAY_COLOR;
        
        _libraryObject = nil;
    }
    return self;
}

- (void)setLibraryObject:(BALibrary *)libraryObject
{
    _libraryObject = libraryObject;
    [[NSUserDefaults standardUserDefaults] setObject:[libraryObject toJSONObject] forKey:BASETTINGS_LIBRARY_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BALibrary *)libraryObject
{
    if (_libraryObject == nil) {
        @try {
            NSDictionary *jsonObj = [[NSUserDefaults standardUserDefaults] dictionaryForKey:BASETTINGS_LIBRARY_KEY];
            if (jsonObj) {
                _libraryObject = [BALibrary objectWithJSONObject:jsonObj];
            }
        }
        @catch (NSException *exception) {
            NSLog(@"Error reading library object from NSUserDefaults: %@",exception);
            _libraryObject = nil;
        }
    }
    return _libraryObject;
}

- (void)libraryObjectChanged
{
    customerColorDark = [UIColor colorWithHTMLColor:[self.libraryObject.style objectForKey:@"uiColorDark"]];
    if (!customerColorDark) {
        customerColorDark = BA_CUSTOM_NAVBAR_DEFAULT_GRAY_COLOR;
    }

    customerColorNormal = [UIColor colorWithHTMLColor:[self.libraryObject.style objectForKey:@"uiColorNormal"]];
    if (!customerColorNormal) {
        customerColorNormal = BA_CUSTOM_NAVBAR_DEFAULT_GRAY_COLOR;
    }
    
    /* deprecated
    if (self.libraryObject!=nil && [self.libraryObject.customerId length]>0) {
        NSString* newCustomerId = self.libraryObject.customerId;
        NSString* branchesListPath = [[self class] getBranchesListPathForCustomer:newCustomerId];
        NSMutableArray* readBranchesAsJson = [NSMutableArray arrayWithContentsOfFile:branchesListPath];
        [self setBranchListFromJson:readBranchesAsJson forCustomer:newCustomerId withBranchesListPath:branchesListPath];
        [self fetchBranchesList];
    }
     */

    [[NSNotificationCenter defaultCenter] postNotificationName:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
}


/* deprecated
-(void)fetchBranchesListIfNeeded
{
    if ([self.branches count]==0) {
        //initiate new fetch from backend
        [self fetchBranchesList];
    }
}
*/

/* deprecated
 Perform getBranches on backend
 *
-(void)fetchBranchesList
{
    if (self.libraryObject != nil) {
        NSString* newCustomerId = self.libraryObject.customerId;

        if (newCustomerId != nil) {
            NSString* branchesListPath = [[self class] getBranchesListPathForCustomer:newCustomerId];
            
            [BARPCManager getBranchesAsyncFromView:self
                                       resultBlock:^(NSArray* result) {
                                           NSMutableArray* branchesAsJson = [NSMutableArray new];
                                           for(BABranch* branch in result) {
                                               [branchesAsJson addObject:[branch toJSONObject]];
                                           }
                                           [branchesAsJson writeToFile:branchesListPath atomically:YES];
                                           NSMutableArray* readBranchesAsJson = [NSMutableArray arrayWithContentsOfFile:branchesListPath];
                                           [self setBranchListFromJson:readBranchesAsJson forCustomer:newCustomerId withBranchesListPath:branchesListPath];
                                           [[NSNotificationCenter defaultCenter] postNotificationName:BA_BRANCHES_LIST_UPDATED object:self];
                                       }
                                        errorBlock:^(int errorCode, NSString *errorMessage) {
                                            DLog(@"WARNING: getBranches failed");
                                            / * Here we will do nothing immediately. If a previous ws call for the same library
                                             was successful, we already have the correct data loaded from cache.
                                             * /
                                            //was: maybe post a new call within a couple of minutes
                                            
                                        }];
        }
    }
    
}

+(NSString*)getBranchesListPathForCustomer:(NSString*)customerId
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* branchesListPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", customerId, @"branches.plist"]];
    return branchesListPath;
}

- (void) setBranchListFromJson:(NSArray*)jsonObjects forCustomer:(NSString*)customerId withBranchesListPath:(NSString*)branchesListPath
{
    //We have to avoid the condition where the user switches library before getBranches RPC returns the branches for a different library.
    //So we check customerId against [self libraryObject].customerId, which could have changed in the mean time.
    if (customerId!= nil && [customerId isEqualToString:[self libraryObject].customerId]) {
        NSMutableArray* readBranchesAsJson = [NSMutableArray arrayWithContentsOfFile:branchesListPath];
        NSMutableArray* newBranches = [NSMutableArray new];
        for(NSDictionary* branchAsJson in readBranchesAsJson) {
            [newBranches addObject:[JSONEncodingHelperMethods parseObjectOfClass:[BABranch class] fromJsonObject:branchAsJson]];
        }
        
        self.branches = newBranches;
    }
}
*/

/*deprecated
-(void)setIsCurrentlyLibrarianMode:(BOOL)shouldBeLibrarianMode
{
    if (shouldBeLibrarianMode) {
        if (self.libraryObject.isLibrarianModeAllowed) {
            _isCurrentlyInLibrarianMode = TRUE;
        }
    } else {
        if (self.libraryObject.isLibraryModeAllowed) {
            _isCurrentlyInLibrarianMode = FALSE;
        }
    }
}
*/

-(BOOL)isLibrarianModeAllowed
{
    return self.libraryObject.isLibrarianModeAllowed;
}


-(BOOL)isUserLibraryModeAllowed
{
    return self.libraryObject.isLibraryModeAllowed;
}

-(BOOL)isImfEnabled
{
    return self.libraryObject.isIMFModeEnabled;
}

-(BOOL)isScannerEnabled
{
    return self.libraryObject.isScannerEnabled;
}


-(NSDictionary *)getSearchFilterTypes
{
    return self.libraryObject.filters;
}

-(NSString *)getDefaultMaterialTypeFilter
{
    return @"materialType";
}

-(UIImage *)getIconForMaterialType:(NSString *)type_string contextIdentifier:(BATypeIconContext)context color:(UIColor *)color{
    if (type_string==nil) {
        type_string=@"";
    }
    
    type_string = [type_string lowercaseString];
    
    NSString* filename = [iconFileNamesForTypeString objectForKey:type_string];
    if (filename==nil) {
        if ([type_string isEqualToString:@"ebog"]) {
            filename = @"bapps_ikon_ebog";
            
        } else if ([type_string isEqualToString:@"netdokument"]) {
            filename = @"bapps_ikon_netdok";
            
        } else if (([type_string rangeOfString:@"lydbog"].location != NSNotFound) && ([type_string rangeOfString:@"net"].location != NSNotFound)) {
            filename = @"bapps_ikon_netlydbog";
            
        } else if ([type_string rangeOfString:@"lydbog"].location != NSNotFound) {
            filename = @"bapps_ikon_lydbog";
            
        } else if (([type_string rangeOfString:@"artikel"].location != NSNotFound)
                      || ([type_string rangeOfString:@"tidsskrift"].location != NSNotFound)
                      || ([type_string rangeOfString:@"avis"].location != NSNotFound)
                      || [type_string isEqualToString:@"årbog"]) {
            
            filename = @"bapps_ikon_artikel";
            
        } else if ([type_string isEqualToString:@"collection"]
                   || [type_string isEqualToString:@"alle"]
                   || [type_string isEqualToString:@"sammensat materiale"]) {
            
            filename = @"bapps_ikon_samling";
            
        } else if ([type_string isEqualToString:@"cd-rom"]
                   || [type_string isEqualToString:@"dvd-rom"]
                   || [type_string isEqualToString:@"spil"]
                   || ([type_string rangeOfString:@"wii"].location != NSNotFound)
                   || ([type_string rangeOfString:@"playstation"].location != NSNotFound)
                   || ([type_string rangeOfString:@"nintendo"].location != NSNotFound)
                   || ([type_string rangeOfString:@"gameboy"].location != NSNotFound)
                   || ([type_string rangeOfString:@"xbox"].location != NSNotFound)
                   || [type_string isEqualToString:@"pc-spil"]
                   ) {
            
            filename = @"bapps_ikon_spil";
            
        } else if ([type_string compare:@"cd"]==NSOrderedSame
                   || [type_string compare:@"lydbog (cd)"]==NSOrderedSame
                   ) {
            
            filename = @"bapps_ikon_cd";
            
        } else if (([type_string rangeOfString:@"musik"].location != NSNotFound)
                   ) {
            
            filename = @"bapps_ikon_musik";
            
        } else if ([type_string isEqualToString:@"grammofonplade"]) {
            
            filename = @"bapps_ikon_lp";
            
        } else if ([type_string compare:@"dvd"]==NSOrderedSame
                   || ([type_string rangeOfString:@"blu-ray"].location != NSNotFound)
                   || [type_string compare:@"video"]==NSOrderedSame
                   || [type_string compare:@"vhs"]==NSOrderedSame
                   || ([type_string rangeOfString:@"film"].location != NSNotFound)
                   ) {
            
            filename = @"bapps_ikon_video";
            
        } else if (([type_string rangeOfString:@"node"].location != NSNotFound)) {
            filename = @"bapps_ikon_noder";
            
        } else if (([type_string rangeOfString:@"(net)"].location != NSNotFound)) {
                filename = @"bapps_ikon_netdok";
                

        } else {
            filename = @"bapps_ikon_bog";
        }
        [iconFileNamesForTypeString setValue:filename forKey:type_string];
    }
    
    
    NSString* icon_image_key = [NSString stringWithFormat:@"%@+context%d+%@", filename, context, [color toHTMLColorString]];
    
    bool is_ipad = RD_IS_IPAD;
    
    UIImage* ret_image = [iconImagesForSize valueForKey:icon_image_key];
    if (ret_image!=nil) {
        return ret_image;
    } else {
        UIImage* originalImage = [UIImage imageNamed:filename];
        
        CGFloat newscale = 1.0;
        switch (context) {
            case BATypeIconContextBAppsMaterialView:
                newscale = is_ipad ? 0.75 : 0.43;
                break;
                
            case BATypeIconContextSearchFilterButton:
                newscale = 0.13;
                break;
            case BATypeIconContextSearchResultsList:
                newscale = is_ipad ? 0.3933 : 0.3333;
                break;
            case BATypeIconContextLibrarianSearchFilters:
                newscale = 0.22;
                break;
            case BATypeIconContextIPadSearchColumnHeader:
                newscale = 0.15;
                break;
                
            default:
                break;
        }
        
        UIImage* coloredImage = [UIImage image:originalImage multiplyWithColor:color newScale:newscale];

        /*
        UIImage *scaledImage = [UIImage imageWithCGImage:[coloredImage CGImage]
                            scale:(newscale)
                      orientation:(coloredImage.imageOrientation)];*/
        

        
        
        [iconImagesForSize setValue:coloredImage forKey:icon_image_key];
        DLog(@"icon image cache image count: %d",[iconImagesForSize count]);
        return coloredImage;
    }
}

-(UIImage*)getCachedNormalCustomerColoredImageNamed:(NSString*)filename
{
    UIColor* color = [self getCustomerColorNormal];
    return [self getCachedImageNamed:filename multiplyWithColor:color];
}

-(UIImage*)getCachedDarkCustomerColoredImageNamed:(NSString*)filename
{
    UIColor* color = [self getCustomerColorDark];
    return [self getCachedImageNamed:filename multiplyWithColor:color];
}

-(UIImage*)getCachedImageNamed:(NSString*)filename multiplyWithColor:(UIColor*)color
{
    NSString* icon_image_key = [NSString stringWithFormat:@"%@+contextOther+%@", filename, [color toHTMLColorString]];
    UIImage* ret_image = [iconImagesForSize valueForKey:icon_image_key];
    if (ret_image!=nil) {
        return ret_image;
    } else {
        UIImage* originalImage = [UIImage imageNamed:filename];
        UIImage* coloredImage = [UIImage image:originalImage multiplyWithColor:color];
        [iconImagesForSize setValue:coloredImage forKey:icon_image_key];
        DLog(@"icon image cache image count: %d",[iconImagesForSize count]);
        return coloredImage;
    }
}


-(UIColor *)getCustomerColorNormal
{
    return customerColorNormal;
    //return [UIColor colorWithRed:255.0/255.0 green:80.0/255.0 blue:18.0/255.0 alpha:1]; //helsingør test
    //return [UIColor colorWithHTMLColor:@"#c7002c"]; //kbh test
}

-(UIColor *)getCustomerColorDark
{
    return customerColorDark;
    //return [UIColor colorWithRed:225.0/255.0 green:70.0/255.0 blue:0.0 alpha:1]; //helsingør test
    //return [UIColor colorWithHTMLColor:@"#920124"]; //kbh test
}


-(NSString *)getLogoUrlStringForType:(BALibrarySettingsLogoType)logoType
{
    switch (logoType) {
        case BALibrarySettingsLogoUrlTypeDefault:
            return [self.libraryObject.logoUrls objectForKey:@"defaultLogoUrl"];
            break;
            
        case BALibrarySettingsLogoUrlTypeLogin:
            return [self.libraryObject.logoUrls objectForKey:@"loginLogoUrl"];
            break;
    }
    return nil;
}

-(NSArray *)branches
{
    return self.libraryObject.materialLocations.branches;
}
@end
